package com.jeeplus.common.utils;

import com.jeeplus.core.persistence.dialect.db.OracleDialect;
import org.springframework.jca.cci.connection.ConnectionHolder;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.resource.ResourceException;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * @title: DbUtils
 * @projectName jeeplus
 * @description: TODO
 * @date 2019/7/1816:30
 */
@Service
@Transactional(readOnly = true)
public class DbUtils extends OracleDialect {
    /**
     * 去除ql的orderBy子句。
     *
     * @Author LH
     * @Description //TODO
     * @Date 16:31 2019/7/18
     * @param qlString
     * @return java.lang.String
     **/
    private String removeOrders(String qlString) {
        Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(qlString);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, "");
        }
        m.appendTail(sb);
        return sb.toString();
    }

    /**
     * 去除qlString的select子句。
     *
     * @return
     */
    @SuppressWarnings("unused")
    private String removeSelect(String qlString) {
        int beginPos = qlString.toLowerCase().indexOf("from");
        return qlString.substring(beginPos);
    }
    public String getCountString(String sql) {
        return MessageFormat.format("select count(*) from ({0}) t ",sql);
    }
    /***
     * 实例对象转换脚本
     *
     * @Author LH
     * @Description //TODO
     * @Date 13:00 2019/10/31
     * @param obj
     * @return java.lang.String
     **/
    public String getColumn(Object obj) throws Exception {
        StringBuffer column = new StringBuffer();
        try {
            String className=obj.getClass().getName();
            Class<?> clz = Class.forName(className);
            Field[] fields = clz.getDeclaredFields();

            int i=0;
            for (Field f : fields) {
                if(i>0){
                    column.append(",");
                }
                column.append(f.getName());

                i++;
            }
        }
        catch (Exception e){
            e.printStackTrace();
            throw new Exception("实例转换失败!");
        }
        return column.toString();
    }

}
